<template>
  <section id="app" class="content">
    <!-- 此处为中间内容，通过 js 动态生成 -->

    <div class="player-background-image">
      <div class="player-content d-flex w">
        <div class="player-album-cover d-flex">
          <!-- 歌曲封面 -->
          <div class="ablum">
            <div class="cover runing">
              <img :src="songs.al.picUrl" alt="" />
            </div>
          </div>
        </div>
        <div class="player-lyric d-flex align-items-start">
          <!-- 歌曲和歌词信息 -->
          <h3 class="song-name">{{ songs.name }}</h3>
          <div class="song-info">
            <span class="song-album">{{ songs.al.name }}</span>
            <span class="singer">{{ songs.ar[0].name }}</span>
            <span class="song-sour">{{ songs.al.name }}</span>
          </div>
          <div class="lyric-wrap">
            <p
              class="song-lyric-item"
              v-for="(ly, index) in formatSongLyric(musicLyric)"
              :key="index"
              :data-time="ly.time"
            >
              {{ ly.lyric }}
            </p>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: "Player",
  data() {
    return {};
  },

  methods: {
    // 拆分出歌词
    formatSongLyric(lyricStr) {
      if (typeof lyricStr != "string") return "歌词加载失败";
      const tempArr = lyricStr.split("\n");
      const lyric = tempArr.map((v, i) => {
        let reg = /^\[(\w*:\w*.?\w*)\](.*)/g;
        let lyricObj = {};
        if (reg.test(v)) {
          let timeStr = RegExp.$1;
          let second = timeStr
            .split(":")
            .reduce(
              (accumulator, curValue) =>
                60 * Number(accumulator) + Number(curValue)
            )
            .toFixed(2);
          lyricObj.time = Number(second);
          lyricObj.lyric = RegExp.$2;
        }
        return lyricObj;
      });
      return lyric;
    },

    /**
     * @description: 滚动条自动滑动的距离
     * @param {*} className
     * @param {*} target
     * @param {*} index
     * @return {*}
     */
    setScrollTop(className, target, index) {
      const ele = document.querySelector(`.${className}`);
      if (typeof target == "number") {
        ele.scrollTop = index * target;
      } else if (typeof target == "string") {
        const { height } = document
          .querySelector(`.${target}`)
          .getBoundingClientRect();
        ele.scrollTop = index * height;
      } else if (target instanceof HTMLElement) {
        const { height } = target.getBoundingClientRect();
        ele.scrollTop = index * height;
      }
    },

    initPlayerEvent() {
      //console.log(this.$store.state.audio,'get');
      const audio = document.querySelector("#myAudio");
      //console.log(audio,'query');
      audio.addEventListener("timeupdate", (e) => {
        // 获得音乐播放当前的时间
        const lyricItem = document.querySelectorAll(".song-lyric-item");
        //console.log(lyricItem,'wwwwwwwwww');
        if (!lyricItem.length) return;

        const currentTime = e.target.currentTime;
        let i = 0;
        Array.from(lyricItem).forEach((item) => {
          const time = item.getAttribute("data-time");
          if (currentTime > time) i++;
          item.classList.remove("active");
        });
        lyricItem[i - 2].classList.add("active");
        if (i > 5) {
          this.setScrollTop("lyric-wrap", "song-lyric-item", i - 1 - 5);
        }
      });
    },

    //添加高斯模糊后的背景图
    imgBlur() {
      const imgBox = document.querySelector(".player-background-image");
      let imgSrc = this.songs.al.picUrl;
      this.blur(imgBox, imgSrc);
    },
    blur(ele, src) {
      //设置 canvas 画布
      const canvas = document.createElement("canvas");
      //width & height越小，图片越模糊
      canvas.width = 100;
      canvas.height = 100;
      // 获得 canvas 上下文
      const ctx = canvas.getContext("2d");
      //Image()函数将会创建一个新的HTMLImageElement实例。它的功能等价于 document.createElement('img')
      const img = new Image();
      img.src = src;
      // 添加属性crossorigin，增加img元素的跨域支持，设置值为anonymous，表示对此元素的 CORS 请求将不设置凭据标志
      img.setAttribute("crossorigin", "anonymous");
      //当img元素加载完成时执行
      img.onload = (e) => {
        const { width, height } = canvas;
        ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height);
        let imgData = ctx.getImageData(0, 0, width, height);

        //高斯模糊

        let gaussData = this.gaussBlur(imgData);
        ctx.putImageData(gaussData, 0, 0);

        //将图片转变为base64的编码格式
        let imgSrc = canvas.toDataURL();
        //设置背景图片
        ele.style.backgroundImage = "url(" + imgSrc + ")";
        console.log("这里是imag----------");
      };
      console.log("这里是imagwai=======----------");
    },
    gaussBlur(imgData) {
      var pixes = imgData.data;
      var width = imgData.width;
      var height = imgData.height;
      var gaussMatrix = [],
        gaussSum = 0,
        x,
        y,
        r,
        g,
        b,
        a,
        i,
        j,
        k,
        len;

      var radius = 10;
      var sigma = 5; //标准差σ，σ描述正态分布资料数据分布的离散程度，σ越大，数据分布越分散，σ越小，数据分布越集中

      a = 1 / (Math.sqrt(2 * Math.PI) * sigma);
      b = -1 / (2 * sigma * sigma);
      //生成高斯矩阵
      for (i = 0, x = -radius; x <= radius; x++, i++) {
        g = a * Math.exp(b * x * x); //标准正态分布函数，正态分布记作N(μ,σ2)，其中μ = 0 ，σ2 = 5
        gaussMatrix[i] = g;
        gaussSum += g;
      }
      //归一化, 保证高斯矩阵的值在[0,1]之间
      for (i = 0, len = gaussMatrix.length; i < len; i++) {
        gaussMatrix[i] /= gaussSum;
      }
      //x 方向一维高斯运算
      for (y = 0; y < height; y++) {
        for (x = 0; x < width; x++) {
          r = g = b = a = 0;
          gaussSum = 0;
          for (j = -radius; j <= radius; j++) {
            k = x + j;
            if (k >= 0 && k < width) {
              //确保 k 没超出 x 的范围
              //r,g,b,a 四个一组
              i = (y * width + k) * 4;
              r += pixes[i] * gaussMatrix[j + radius];
              g += pixes[i + 1] * gaussMatrix[j + radius];
              b += pixes[i + 2] * gaussMatrix[j + radius];
              // a += pixes[i + 3] * gaussMatrix[j];
              gaussSum += gaussMatrix[j + radius];
            }
          }
          i = (y * width + x) * 4;
          // 除以 gaussSum 是为了消除处于边缘的像素, 高斯运算不足的问题
          // console.log(gaussSum)
          pixes[i] = r / gaussSum;
          pixes[i + 1] = g / gaussSum;
          pixes[i + 2] = b / gaussSum;
          // pixes[i + 3] = a ;
        }
      }
      //y 方向一维高斯运算
      for (x = 0; x < width; x++) {
        for (y = 0; y < height; y++) {
          r = g = b = a = 0;
          gaussSum = 0;
          for (j = -radius; j <= radius; j++) {
            k = y + j;
            if (k >= 0 && k < height) {
              //确保 k 没超出 y 的范围
              i = (k * width + x) * 4;
              r += pixes[i] * gaussMatrix[j + radius];
              g += pixes[i + 1] * gaussMatrix[j + radius];
              b += pixes[i + 2] * gaussMatrix[j + radius];
              // a += pixes[i + 3] * gaussMatrix[j];
              gaussSum += gaussMatrix[j + radius];
            }
          }
          i = (y * width + x) * 4;
          pixes[i] = r / gaussSum;
          pixes[i + 1] = g / gaussSum;
          pixes[i + 2] = b / gaussSum;
        }
      }
      //end
      return imgData;
    },
  },
  computed: {
    songs() {
      return this.$store.state.musicDetail;
    },
    musicLyric() {
      return this.$store.state.musicLyric;
    },
  },
  beforeCreate() {
    this.$store.dispatch("musicLyric", this.$store.state.musicId);
  },
  mounted() {
    //console.log('加载完毕');
    this.initPlayerEvent();
    this.imgBlur();
    this.$store.commit("ISRE", false);
    console.log(this.$store.state.musicLyric);
  },
};
</script>

<style>
/* player.css */
.player-content {
  height: 100%;
}

.player-content .player-album-cover {
  height: 100%;
  width: 40%;
  /* position:relative;
    left: -270px; */
}

.player-content .player-album-cover .ablum {
  background: url("../../assets/image/singlecover.png");
  width: 300px;
  height: 295px;
  background-size: cover;
  position: relative;
  border-radius: 50%;
}

.player-content .player-album-cover .ablum .cover {
  width: 65%;
  height: 65%;
  border-radius: 50%;
  overflow: hidden;
  position: absolute;
  top: 18%;
  left: 18%;
  box-shadow: 0 0 5px 5px #222;
}

.player-content .player-album-cover .ablum img {
  width: 100%;
  height: 100%;
}

.player-content .player-album-cover .ablum .cover,
.running {
  animation: imgRotate 30s linear infinite;
}

@keyframes imgRotate {
  /* from {
      transform: rotate(0deg);
    }
  
    to {
      transform: rotate(360deg);
    } */
  0% {
    transform: rotate(0deg);
  }

  30% {
    transform: rotate(120deg);
  }

  72% {
    transform: rotate(240deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.player-content .player-lyric {
  flex-grow: 1;
  flex-direction: column;
}

.player-lyric .song-name {
  flex-grow: 1;
  font-size: 20px;
  margin: 10px 0;
  font-weight: bold;
}

.player-lyric .song-info {
  margin: 5px 0;
}

.player-lyric .song-info > span {
  margin-right: 10px;
}

.player-lyric .lyric-wrap {
  height: 350px;
  width: 90%;
  overflow-y: scroll;
  margin-top: 10px;
}

.player-lyric .lyric-wrap .song-lyric-item {
  width: 100%;
  padding-bottom: 8px;
  text-align: center;
}

.player-background-image {
  margin-top: -10px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-size: cover;
}

.player-content {
  height: 100%;
  /* 新增 */
  position: relative;
}

/* home.css */
.wrapper .content {
  width: 100%;
  /* 新增 */
  position: relative;
  min-height: 580px;
  margin-top: 10px;
}

.player-lyric .lyric-wrap .song-lyric-item.active {
  color: rgba(21, 218, 14, 0.7);
}
</style>
